<script setup lang="ts">
import MenuHeader from './components/MenuHeader.vue'
import CartBox from "./components/CartBox.vue";
import CartDetail from "./components/CartDetail.vue";
import VerticalClassifyList from "./components/VerticalClassifyList.vue";
import api from '@/api';
import {reactive, toRefs} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
onLoad(()=>{
  getCart()
})
const getCart = async ()=>{
  const res = await api.cart.indexApi();
  if(res.code === 1){
    state.cartTotal = res.data.total;
    state.totalPrice = res.data.totalPrice;
    state.cartList = res.data.list;
  }
}
const state = reactive({
  cartPopupVisible: false,
  cartTotal: 0,
  totalPrice: 0,
  cartList: [],
})
const {
  cartPopupVisible,
  cartTotal,
  totalPrice,
  cartList,
} = toRefs(state)

const closeCartDetailPopup = () => {
  cartPopupVisible.value = false;
}
const openCartDetailPopup = () => {
  cartPopupVisible.value = true;
}

// 更新购物车
const onCartUpdate = async (e) => {
  await api.cart.updateApi(e).then(res=>{
    if(res.code === 1){
      getCart()
    }
  })
}
// 删除购物车
const onCartDel = async (e) => {
  await api.cart.delApi(e).then(res=>{
    if(res.code === 1){
      getCart()
    }
  })
}
// 清空购物车
const onCartClear = async () => {
  await api.cart.clearApi().then(res=>{
    if(res.code === 1){
      getCart()
    }
  })
}
// 重新获取购物车信息
const reCart = () => {
  getCart()
}


</script>
<template>
  <view class="container">
    <MenuHeader></MenuHeader>
    <VerticalClassifyList @reCart="reCart"></VerticalClassifyList>
    <!-- 购物车栏 begin -->
    <CartBox :cartTotal=cartTotal :totalPrice=totalPrice @open="openCartDetailPopup"></CartBox>
    <!-- 购物车栏 end -->
    <!-- 购物车详情popup -->
    <CartDetail :cartPopupVisible="cartPopupVisible" :cartList=cartList @close="closeCartDetailPopup" @onCartUpdate="onCartUpdate" @onCartDel="onCartDel" @onCartClear="onCartClear"></CartDetail>
    <!-- 购物车详情popup -->
  </view>
</template>


<style lang="scss" scoped>
.container {
  height: calc(100vh);
  /* #ifdef H5 */
  height: calc(100vh - var(--window-top));
  /* #endif */
  display: flex;
  flex-direction: column;
}
</style>